#include "util.h"
#include "redis.h"
#include "ludb.h"
#include <sstream>
#include <string>

static bool redis_init = false;

CRedis::CRedis(std::string addr, std::string db)
    : m_strAddr(addr)
    , m_strDB(db)
    , m_pConn(NULL)
{
    if(!redis_init) {
        ludb_init_redis();
        redis_init = false;
    }
    m_pConn = ludb_connect(ludb_db_type_t::ludb_db_redis, m_strAddr.c_str(), m_strDB.c_str(), NULL);
}

CRedis::~CRedis() {
    if(m_pConn)
        ludb_free_conn((ludb_conn_t*)m_pConn);
}

bool CRedis::Update(SubscribeData &data) {
    std::stringstream ss;
    ss << "SET Subscribe:" << data.subscribe_id
        << " " << data.subscribe_code;

    string cmd = ss.str();
    Log::debug(cmd.c_str());
    ludb_stmt_t *stmt = ludb_create_stmt((ludb_conn_t*)m_pConn);
    if(!ludb_execute_stmt(stmt, cmd.c_str())) {
        ludb_free_stmt(stmt);
        return false;
    }
    ludb_free_stmt(stmt);

    return true;
}

bool CRedis::Remove(std::string subscribe_id) {
    std::stringstream ss;
    ss << "DEL Subscribe:" << subscribe_id;

    std::string cmd = ss.str();
    Log::debug(cmd.c_str());
    ludb_stmt_t *stmt = ludb_create_stmt((ludb_conn_t*)m_pConn);
    if(!ludb_execute_stmt(stmt, cmd.c_str())) {
        ludb_free_stmt(stmt);
        return false;
    }
    ludb_free_stmt(stmt);

    return true;
}

std::vector<SubscribeData> CRedis::Get() {
    std::string cmd = "KEYS *";
    ludb_stmt_t *stmt = ludb_create_stmt((ludb_conn_t*)m_pConn);
    ludb_execute_stmt(stmt, cmd.c_str());
    ludb_rest_t* rest = ludb_result(stmt);
    vector<string> vecKey;
    while (ludb_result_next(rest)) {
        string key = ludb_rest_get_char(rest, 1);
        vecKey.push_back(key);
    }
    ludb_free_result(rest);
    ludb_free_stmt(stmt);
    Log::debug("devnum: %d", vecKey.size());

    std::vector<SubscribeData> ret;
    for(auto key:vecKey) {
        vector<string> tmp = util::String::split(key, ':');
        if(tmp.size() != 2)
            continue;
        SubscribeData data;
        data.subscribe_id = tmp[1];

        cmd = "GET " + key;
        ludb_stmt_t *stmt = ludb_create_stmt((ludb_conn_t*)m_pConn);
        ludb_execute_stmt(stmt, cmd.c_str());
        ludb_rest_t* rest = ludb_result(stmt);
        if(rest != NULL){
            data.subscribe_code = ludb_rest_get_char(rest, 1);
            ret.push_back(data);
            ludb_free_result(rest);
        }
        ludb_free_stmt(stmt);
    }

    return ret;
}